#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 创建临时文件和文件夹
问题: 你需要在程序执行时创建一个临时文件或目录，并希望使用完之后可以自动销毁掉。
提示 :
"""

from tempfile import TemporaryFile, NamedTemporaryFile, TemporaryDirectory
import tempfile

print(f"{tempfile.gettempdir() = }")

def recipe1():
    # with TemporaryFile('w+t', encoding='utf-8', errors='ignore') as f:
    with TemporaryFile('w+t') as f:
        # Read/write to the file
        f.write('Hello Word\n')
        f.write('Testing\n')

        f.seek(0)
        print(f"{f.read() = }")

def recipe2():
    # with NamedTemporaryFile('w+t', delete=False) as f:
    with NamedTemporaryFile('w+t') as f:
        print('filename is:', f.name)

def recipe3():
    with TemporaryDirectory() as dirname:
        print('dirname is', dirname)

def recipe4():
    '''更低的级别'''
    print(f"{tempfile.mkstemp() = }")
    print(f"{tempfile.mkdtemp() = }")

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()
    print('recipe3'.center(20, '*'))
    recipe3()
    print('recipe4'.center(20, '*'))
    recipe4()

if __name__ == '__main__':
    main()                 